package com.feng.study.demo.juc;

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

/**
 * Thread与Runnable与Callable
 */
public class JUCDemo01 {
    public static void main(String[] args) throws InterruptedException {
        // 新建子线程
        MyThread myThread = new MyThread();
        // 启动子线程
        myThread.start();

        // 新建任务
        MyRunnable run = new MyRunnable();
        // 新建线程，设置任务
        Thread thread2 = new Thread(run);
        // 启动子线程
        thread2.start();

        // 创建Callable
        MyCallable call = new MyCallable(10);
        // 创建任务(适配器类FutureTask，适配器模式)
        FutureTask<Integer> task = new FutureTask<Integer>(call);
        // 新建线程，设置任务
        Thread thread3 = new Thread(task);
        // 启动子线程
        thread3.start();

        // 效果对比
        String threadName = Thread.currentThread().getName();
        for (int i = 0; i < 10; i++) {
            Thread.sleep(100);
            System.out.println(threadName + "--------" + i);
        }
    }

}

/**
 * 继承Thread
 */
class MyThread extends Thread{
    @Override
    public void run() {
        String threadName = Thread.currentThread().getName();
        for (int i = 0; i < 10; i++) {
            try {
                Thread.sleep(100);
                System.out.println("Thread:"+threadName + "--------" + i);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

/**
 * 实现Runnable接口
 * 没有返回值
 */
class MyRunnable implements Runnable {
    @Override
    public void run() {
        String threadName = Thread.currentThread().getName();
        for (int i = 0; i < 10; i++) {
            try {
                Thread.sleep(100);
                System.out.println("Runnable:"+threadName + "--------" + i);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

/**
 * 实现Callable接口
 * 又返回值
 * call()方法允许抛出异常
 */
class MyCallable implements Callable<Integer> {
    private int num;

    public MyCallable(int num) {
        this.num = num;
    }
    @Override
    public Integer call() throws Exception {
        // 从 1 到 num 的合计
        int sum = 0;
        for (int i = 1; i <= num; i++) {
            Thread.sleep(1000);
            sum += i;
        }
        System.out.println("Callable:"+sum);
        return sum;
    }
}